package com.chinanet.utils.telnet;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HCNetworkTelnet {
    private TelnetClient telnet = new TelnetClient();
    private InputStream in = null;
    private PrintStream out = null;


    public int initTelnet(String ip, int port, String user, String password, StringBuffer sbb) {
        try {
            telnet.connect(ip, port);
            in = telnet.getInputStream();
            out = new PrintStream(telnet.getOutputStream());
            int i = login(user, password, sbb);
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 登录 * * @param user * @param password
     */
    public int login(String OPNAME, String password, StringBuffer sbb) {
        write("LGI:HLRSN=1,OPNAME=\"" + OPNAME + "\",PWD=\"" + password + "\";");
        if (readUntil("END", sbb) != null) {
            return 0;
        } else {
            return 1;
        }
    }


    /**
     * 读取分析结果 * * @param pattern * @return
     */
    public String readUntil(String pattern, StringBuffer sbb) {
        try {
            char lastChar = pattern.charAt(pattern.length() - 1);
            StringBuffer sb = new StringBuffer();
            char ch = (char) in.read();
            while (true) {
                sb.append(ch);
                sbb.append(ch);
                if (ch == lastChar) {
                    if (sb.toString().endsWith(pattern)) {
                        return sb.toString();
                    }
                }

                ch = (char) in.read();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 写操作 * * @param value
     */
    public void write(String value) {
        try {
            out.println(value);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向目标发送命令字符串 * * @param command * @return
     */
    public int sendCommand(String command, StringBuffer sbb) {
        try {
            write(command);
            if (readUntil("END", sbb) != null) {
                return 0;
            } else {
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }


    /**
     * 关闭连接
     */
    public void disconnect() {
        try {
            telnet.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Map<String, Object> init(String phonenum) {
        StringBuffer sbb = new StringBuffer();
        Map<String, Object> map = new HashMap<>();
        String ip = "134.96.189.243";
        int port = 7777;
//        String phonenume="861530576097";
        System.out.println(phonenum + "*******");
        String user = "shengx";
        String password = "TzSx1710";
        HCNetworkTelnet telnet = new HCNetworkTelnet();
        int flag = 0;
        try {
            int loginFlag = telnet.initTelnet(ip, port, user, password, sbb);
            if (loginFlag == 0) {
                int sendCommandFlag = telnet.sendCommand("LST CDYNSUB: MDN=\"" + phonenum + "\";", sbb);
                if (sendCommandFlag == 0) {
                    System.out.println("显示结果");
                    System.out.println(sbb.toString());
                    map.putAll(dealThings(sbb.toString()));
                    map.put("flag", 0);
                    flag = 0;
                } else {
                    flag = 1;
                    map.put("info", "命令发送失败");
                    System.out.println("login failed..");
                }
            } else {
                flag = 1;
                map.put("info", "登录失败");
                System.out.println("login failed..");
            }

        } catch (Exception e) {
            e.printStackTrace();
            map.put("info", "服务器报错");
            flag = 1;
        } finally {
            if (flag == 1) {
                map.put("flag", 1);
                map.put("ExecutionTime", "");
                map.put("IMSI", "");
                map.put("MDN", "");
                map.put("MsStatus", "");
                map.put("MSCID", "");
                map.put("RegTime", "");
            }
            try {
                map.put("log", new String(sbb.toString().getBytes("ISO-8859-1"), "GBK"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                map.put("log", sbb.toString());
            }
            telnet.disconnect();
        }
        return map;

    }


//    public static void main(String[] args) {  
//        try {  
//            System.out.println("启动Telnet...");  
//            
//            init("8615305760979");
//        } catch (Exception e) {  
//            e.printStackTrace();  
//        }  
//    }


    public static Map<String, Object> dealThings(String txt) {
        System.out.println("length: " + txt.length());
        Map<String, Object> map = new HashMap<>();
        if (txt != null && txt.length() > 500) {
            System.out.println("yoyoyoyo");
            String ExecutionTime = returnMatcher("---    END", "SMU", txt);
            ExecutionTime = ExecutionTime.substring(ExecutionTime.length() - 21, ExecutionTime.length() - 1).trim();
            System.out.println("ExecutionTime: " + ExecutionTime + " " + ExecutionTime.length());
            map.put("ExecutionTime", ExecutionTime);

            System.out.println("yoyoyoyo");
            String IMSI = returnMatcher("IMSI  =", "MsStatus  =", txt);
            IMSI = returnMatcher("", "MDN  =", IMSI).trim();
            System.out.println("IMSI: " + IMSI + " " + IMSI.length());
            map.put("IMSI", IMSI);

            String MDN = returnMatcher("MDN  =", "MsStatus  =", txt).trim();
            System.out.println("MDN: " + MDN + " " + MDN.length());
            map.put("MDN", MDN);

            String MsStatus = returnMatcher("MsStatus  =", "PC_SSN  =", txt).trim();
            System.out.println("MsStatus: " + MsStatus + " " + MsStatus.length());
            map.put("MsStatus", MsStatus);

            String MSCID = returnMatcher("MSCID  =", "VLRID  =", txt).trim();
            System.out.println("MSCID: " + MSCID + " " + MSCID.length());
            map.put("MSCID", MSCID);

            String RegTime = returnMatcher("RegTime  =", "VOICE_WaitMsg  =", txt).trim();
            System.out.println("RegTime: " + RegTime + " " + RegTime.length());
            map.put("RegTime", RegTime);
            map.put("info", "");
        } else {
            map.put("ExecutionTime", "");
            map.put("IMSI", "");
            map.put("MDN", "");
            map.put("MsStatus", "");
            map.put("MSCID", "");
            map.put("info", "解析失败");
            map.put("RegTime", "");
        }
        return map;
    }

    public static String returnMatcher(String leftPart, String rightPart, String txt) {
        try {
            String returnBack = "";
            String regex = leftPart + "([\\s\\S].*)" + rightPart;
            Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE
                    | Pattern.DOTALL);
            Matcher matcher = pattern.matcher(txt);

            while (matcher.find()) {
                returnBack = matcher.group(1);
            }
            return returnBack;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


}  


